import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Space } from 'antd';
import { useRef } from 'react';
import { t } from '../utils';

interface CommonTableProps<T = any> {
  columns: ProColumns<T>[];
  dataSource?: T[];
  loading?: boolean;
  pagination?: any;
  rowKey?: string | ((record: T) => string);
  tableProps?: Record<string, any>;
  showAddButton?: boolean;
  addButtonText?: string;
  onAdd?: () => void;
  extraButtons?: React.ReactNode;
  title?: string;
  bordered?: boolean;
}

const CommonTable = <T extends Record<string, any>>({
  columns,
  dataSource,
  loading,
  pagination,
  rowKey = 'id',
  tableProps,
  showAddButton = true,
  addButtonText = 'Add',
  onAdd,
  extraButtons,
  title,
  bordered = true,
}: CommonTableProps<T>) => {
  const actionRef = useRef<ActionType>();

  return (
    <div
      style={{
        background: '#fff',
        borderRadius: '8px',
        boxShadow:
          '0 1px 2px 0 rgba(0, 0, 0, 0.03), 0 1px 6px -1px rgba(0, 0, 0, 0.02), 0 2px 4px 0 rgba(0, 0, 0, 0.02)',
      }}
    >
      <ProTable<T>
        actionRef={actionRef}
        columns={columns}
        dataSource={dataSource}
        loading={loading}
        rowKey={rowKey}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
          ...pagination,
        }}
        bordered={bordered}
        cardBordered={false}
        headerTitle={title}
        toolBarRender={() => [
          <Space key="toolbar">
            {showAddButton && onAdd && (
              <Button type="primary" icon={<PlusOutlined />} onClick={onAdd}>
                {t('common', 'create') || addButtonText}
              </Button>
            )}
            {extraButtons}
          </Space>,
        ]}
        options={{
          setting: {
            listsHeight: 400,
          },
          reload: () => {
            actionRef.current?.reload();
          },
          density: true,
          fullScreen: true,
        }}
        search={false}
        dateFormatter="string"
        {...tableProps}
      />
    </div>
  );
};

export default CommonTable;
